package bean.managed;

import entity.ShippingRequestEntity;
import bean.managed.util.JsfUtil;
import bean.session.ShippingRequestEntityFacade;

import java.util.List;
import entity.PurchaseOrderEntity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.SelectItem;
import managedbean.AbstractBacking;

@ManagedBean(name = "shippingRequestEntityController")
@SessionScoped
public class ShippingRequestEntityController extends AbstractBacking implements Serializable {

    private ShippingRequestEntity current;
    private Collection<ShippingRequestEntity> shippingRequests;
    @EJB
    private bean.session.ShippingRequestEntityFacade ejbFacade;
    @ManagedProperty(value = "#{purchaseOrderEntityController}")
    private PurchaseOrderEntityController purchaseOrderEntityController;
    @ManagedProperty(value = "#{packingOrderEntityController}")
    private PackingOrderEntityController packingOrderEntityController;

    public ShippingRequestEntityController() {
    }

    public ShippingRequestEntity getSelected() {
        if (current == null) {
            current = new ShippingRequestEntity();
        }
        return current;
    }

    public void setSelected(ShippingRequestEntity selected) {
        System.out.println("setting selected: " + selected);
        setCurrent(selected);
    }

    private ShippingRequestEntityFacade getFacade() {
        return ejbFacade;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        return "View";
    }

    public String prepareCreate() {
        current = new ShippingRequestEntity();
        return "Create";
    }

    public String create() {
        try {
            current.created(getLoginPerson());
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ShippingRequestEntityCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        return "Edit";
    }

    public String update() {
        try {
            current.modified(getLoginPerson());
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ShippingRequestEntityUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public void updateOrEditWithoutRedirect() {
        System.out.println("shipppingRequest: in updateOrCreate without redirect: " + current);
        try {
            checkDates();
            if (getSelected().getId() == null) {
                PurchaseOrderEntity p = purchaseOrderEntityController.getSelected();
                System.out.println("purchase order: " + p);
                current.setPurchaseOrder(p);
                p.getShippingRequests().add(current);

                //current.setShippingDate(p.getPreferredLeadTime());

                current.created(getLoginPerson());
                System.out.println("New request created: " + current);
                current = null;
            } else {
                current.modified(getLoginPerson());
                getFacade().edit(current);
                System.out.println("request edited: " + current);
                current = null;
            }
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ShippingRequestEntityUpdated"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    public void checkDates() {
        if (current.getPurchaseOrder() != null) {
            if (!current.getShippingDate().equals(current.getPurchaseOrder().getPreferredLeadTime()))
                JsfUtil.addErrorMessage("Shipping Date not equal to Required Lead Time!");
            else if (current.getPurchaseOrder().getSalesOrder() != null) {
                if (current.getPurchaseOrder().getSalesOrder().getBackorder() != null) {
                    if (current.getPurchaseOrder().getSalesOrder().getBackorder().getConfirmedLeadTime() != null) {
                        if (!current.getShippingDate().equals(current.getPurchaseOrder().getPreferredLeadTime()) && !current.getShippingDate().equals(current.getPurchaseOrder().getSalesOrder().getBackorder().getConfirmedLeadTime())) {
                            JsfUtil.addErrorMessage("Shipping Date not equal to Required Lead Time/Confirmation Lead Time!");
                        }
                    }
                }
            }
        }
    }

    public void removeFromPurchaseOrder() {
        PurchaseOrderEntity p = purchaseOrderEntityController.getSelected();
        p.getShippingRequests().remove(current);
    }

    public void destroy() {
        performDestroy();
        recreateModel();
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        return "List";
    }

    private void performDestroy() {
        try {
            removeFromPurchaseOrder();

            if(getSelected().getId()!=null){
                getFacade().originalRemove(current);
            }else
                current=null;
            
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ShippingRequestEntityDeleted"));
        } catch (Exception e) {
            e.printStackTrace();
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    public void recreateModel() {
        current = null;
        System.out.println("shipping request: model recreated");
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public SelectItem[] getDateSelectOne() {
        return JsfUtil.getSelectItems(findDates(), true);
    }

    public List<Date> findDates() {
        List<Date> date = new ArrayList<Date>();
        if (current.getPurchaseOrder() != null) {
            date.add(current.getPurchaseOrder().getPreferredLeadTime());
            if (current.getPurchaseOrder().getSalesOrder() != null) {
                if (current.getPurchaseOrder().getSalesOrder().getBackorder() != null) {
                    if (current.getPurchaseOrder().getSalesOrder().getBackorder().getConfirmedLeadTime() != null) {
                        date.add(current.getPurchaseOrder().getSalesOrder().getBackorder().getConfirmedLeadTime());
                    }
                }
            }
        }
        return date;
    }

    @FacesConverter(forClass = ShippingRequestEntity.class)
    public static class ShippingRequestEntityControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            ShippingRequestEntityController controller = (ShippingRequestEntityController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "shippingRequestEntityController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof ShippingRequestEntity) {
                ShippingRequestEntity o = (ShippingRequestEntity) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + ShippingRequestEntityController.class.getName());
            }
        }
    }

    public PurchaseOrderEntityController getPurchaseOrderEntityController() {
        return purchaseOrderEntityController;
    }

    public void setPurchaseOrderEntityController(PurchaseOrderEntityController purchaseOrderEntityController) {
        this.purchaseOrderEntityController = purchaseOrderEntityController;
    }

    public PackingOrderEntityController getPackingOrderEntityController() {
        return packingOrderEntityController;
    }

    public void setPackingOrderEntityController(PackingOrderEntityController packingOrderEntityController) {
        this.packingOrderEntityController = packingOrderEntityController;
    }

    public ShippingRequestEntity getCurrent() {
        return current;
    }

    public void setCurrent(ShippingRequestEntity current) {
        this.current = current;
    }

    public Collection<ShippingRequestEntity> getShippingRequests() {
        shippingRequests = purchaseOrderEntityController.getSelected().getShippingRequests();
        return shippingRequests;
    }

    public void setShippingRequests(Collection<ShippingRequestEntity> shippingRequests) {
        this.shippingRequests = shippingRequests;
    }

    public Collection<ShippingRequestEntity> getShippingRequestsForPackingOrder() {
        shippingRequests = packingOrderEntityController.getSelected().getProductToQuantity();
        return shippingRequests;
    }

    public void doNothing() {
        System.out.println("doing nothing..");
    }
}
